package com.leyou.auth.service.impl;

import com.leyou.auth.constans.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.client.UserClient;
import org.apache.catalina.connector.Response;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constans.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constans.JwtConstants.DOMAIN;

@Service
public class UserAuthServiceImpl implements UserAuthService {


    private UserClient userClient;

    private JwtUtils jwtUtils;

    public UserAuthServiceImpl(UserClient userClient, JwtUtils jwtUtils) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {

        try {
            // 1.根据用户名和密码查询用户
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);
            // 2.判断查询结果
            if (user == null) {
                // 查询失败
                throw new LyException(400, "用户名或密码错误");
            }
            // 3.如果正确，生成JWT
            String jwt = jwtUtils.createJwt(UserDetails.of(user.getId(), user.getUsername()));
            // 4.写入用户cookie
            writeCookie(response, jwt);
        } catch (LyException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void logOut(HttpServletRequest request, HttpServletResponse response) {
        //1.获取jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if (StringUtils.isEmpty(jwt)) {
            //用户未登录
        }
        try {
            //2.获取用户id
            Long userId = jwtUtils.parseJwt(jwt).getUserDetail().getId();
            //3.删除redis中jti
            jwtUtils.clearJti(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.删除cookie,设置cookie为0
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME, DOMAIN, response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        // cookie的作用域
        cookie.setDomain(DOMAIN);
        // 防止js获取cookie信息
        cookie.setHttpOnly(true);
        //cookie的有效时间
        cookie.setMaxAge(-1);
        // cookie作用范围
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}